package com.wry.im.init;

import com.wry.im.handler.CloseServerHandler;
import com.wry.im.handler.HttpServerHandler;
import com.wry.im.handler.MessageServerHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.wry.im.handler.MessageServerHandler.channelMap;

/**
 * <h1> netty初始化通道 <h1>
 *
 * @author wry
 * @since 2023/4/27 14:27
 */
@Component
@Slf4j
public class ServerChannelInitializer extends ChannelInitializer<Channel> {

    /*
    * 首先websocket本身是基于http协议,在第一次请求实际上是发起了一次http请求,
    * 然后协议升级成为了websocket,维持了socket连接,所以在实际处理socket请求前可以通过处理http请求的方式来进行身份的校验
    */

    @Resource
    private MessageServerHandler messageServerHandler;
    @Resource
    private HttpServerHandler httpServerHandler;
    @Resource
    private CloseServerHandler closeServerHandler;

    @Override
    protected void initChannel(Channel socketChannel) throws Exception {
        // HttpServerCodec：将请求和应答消息解码为HTTP消息
        socketChannel.pipeline().addLast("http-codec",new HttpServerCodec());
        // HttpObjectAggregator：将HTTP消息的多个部分合成一条完整的HTTP消息
        socketChannel.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
        // ChunkedWriteHandler：向客户端发送HTML5文件
        socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
        //初始化连接的处理handler
        socketChannel.pipeline().addLast("httpHandler", httpServerHandler);
        //消息处理handler
        socketChannel.pipeline().addLast("messageHandler", messageServerHandler);
        //关闭后的消息处理
        socketChannel.pipeline().addLast("closeHandler", closeServerHandler);
    }
}
